package priorityqueue;

import java.util.Arrays;

public class MyPriorityQueue {
    public int[] data;
    public int size;

    public MyPriorityQueue() {
        this.data = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param arr 堆的数组
     */
    public void createHeap(int[] arr) {
        for (int parent = (size - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent, size);
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public MyPriorityQueue(int[] arr) {
        this.data = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
            size++;
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root * 2 + 1;
        while (child < len) {
            if (child + 1 < len && data[child] < data[child + 1]) {
                child++;
            }
            if (data[child] > data[root]) {
                swap(data, child, root);
                root = child;
                child = root * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (data[child] > data[parent]) {
                swap(data, child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val 入队的元素
     */
    public void push(int val) {
        if (isFull()) {
            this.data = Arrays.copyOf(data, data.length + (data.length >> 1));
        }
        data[size] = val;
        shiftUp(size++);
    }

    public boolean isFull() {
        return size == data.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public int pollHeap() {
        if (isEmpty()) {
            throw new RuntimeException("heap is empty");
        }
        int ret = data[0];
        data[0] = data[size - 1];
        size--;
        shiftDown(0, size);
        return ret;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 获取堆顶元素
     * @return 堆顶元素
     */
    public int peekHeap() {
        return data[0];
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(data[i]);
            if (i != size - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
